package com.example.nettydemo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.example.nettydemo.entity.Message;
import com.example.nettydemo.server.NettyChannelHandlerPool;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author WZW
 * @date 2020/5/9
 */
public class MessageUtil {

    private static final SerializeConfig config = new SerializeConfig();
    static {
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    }

    public static void sendMessageToALl(Message message) {
        Set<String> keySet = NettyChannelHandlerPool.getAllGuidSet();
        List<String> deleteGuids = new ArrayList<>();
        if (keySet.size() > 0) {
            keySet.forEach((key) -> {
                ChannelId channelId = NettyChannelHandlerPool.getChannel(key);
//                System.out.println("channelId = " + channelId);
                Channel channel = NettyChannelHandlerPool.channelGroup.find(channelId);
//                System.out.println("channel = " + channel);
                if (channel == null) {
                    //通道为null，需要从map中删除，先记录一下，循环结束再删
                    deleteGuids.add(key);
                    return;
                }
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message, config)));
            });
            //从map中删除已经无用的通道
            deleteGuids.forEach(guid -> {
                NettyChannelHandlerPool.removeChannel(guid);
                NettyChannelHandlerPool.removeGuid(guid);
            });
        }
    }

    public static void sendMessageToOne(Message message) {
        String guid = message.getGuid();
        ChannelId channelId = NettyChannelHandlerPool.getChannel(guid);
        Channel channel = NettyChannelHandlerPool.channelGroup.find(channelId);
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message, config)));
    }
}
